package com.fei.controller;

import com.fei.bean.UserBean;
import com.fei.service.FileService;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.io.File;

@Controller
public class EmailController {

    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    FileService fileService;

    @SneakyThrows
    @RequestMapping("/exception")
    public String email(MultipartFile file1, String text, HttpSession session){
        UserBean user = (UserBean)session.getAttribute("user");
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //组装
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true);
        if(user == null){
            helper.setSubject("用户反馈");
        }else{
            helper.setSubject("来自"+user.getName()+"的反馈");
        }
        helper.setText(text);
//        发送附件
        File path = fileService.ParentPath();
//        判断有没有上传
        if(StringUtils.isNotBlank(file1.getOriginalFilename())){
            String filePath = path + "//data//email//1";
            String file1Suffix = fileService.FileSuffix(file1.getOriginalFilename());
            Boolean f2 = fileService.FileUpload(filePath,"1."+file1Suffix,file1);
            helper.addAttachment("1.jpg",new File(filePath+"//1."+file1Suffix));
        }

//        发给自己
        helper.setTo("2497282263@qq.com");
        helper.setFrom("2497282263@qq.com");
        mailSender.send(mimeMessage);
        if (StringUtils.isNotBlank(file1.getOriginalFilename())){
//            上传完就删除
            fileService.FileDelete(new File(path+"//data//email"));//上传完就删除
        }
        return "redirect:/";
    }

}
